const mysql = require('mysql2/promise');

// 数据库配置 - 硬编码配置
const dbConfig = {
  host: 'localhost',
  user: 'root',
  password: '123456',
  database: 'qc_print_ticket'
};

// 创建数据库连接池
const pool = mysql.createPool({
  host: dbConfig.host,
  user: dbConfig.user,
  password: dbConfig.password,
  database: dbConfig.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 测试数据库连接
async function testConnection() {
  try {
    const connection = await pool.getConnection();
    console.log('数据库连接成功');
    connection.release();
  } catch (error) {
    console.error('数据库连接失败:', error.message);
    // 在开发环境中，如果数据库不存在，尝试创建数据库
    if (error.code === 'ER_BAD_DB_ERROR') {
      try {
        const tempPool = mysql.createPool({
          host: dbConfig.host,
          user: dbConfig.user,
          password: dbConfig.password,
          waitForConnections: true,
          connectionLimit: 10,
          queueLimit: 0
        });
        const connection = await tempPool.getConnection();
        await connection.query(`CREATE DATABASE IF NOT EXISTS ${dbConfig.database}`);
        console.log(`数据库 ${dbConfig.database} 创建成功`);
        connection.release();
        tempPool.end();
        // 重新连接到创建的数据库
        await pool.query('SELECT 1');
        console.log('重新连接到新创建的数据库成功');
      } catch (createError) {
        console.error('创建数据库失败:', createError.message);
      }
    }
  }
}

// 初始化数据库表结构
async function initDatabase() {
  try {
    const connection = await pool.getConnection();
    
    // 创建订单表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS orders (
        id INT AUTO_INCREMENT PRIMARY KEY,
        order_no VARCHAR(50) NOT NULL UNIQUE,
        customer_name VARCHAR(100) NOT NULL,
        customer_phone VARCHAR(20),
        total_amount DECIMAL(10,2) NOT NULL,
        order_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        print_status TINYINT DEFAULT 0,
        items JSON NOT NULL
      )
    `);
    
    // 创建打印记录表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS print_records (
        id INT AUTO_INCREMENT PRIMARY KEY,
        order_id INT NOT NULL,
        print_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
        printer_info VARCHAR(200),
        print_status VARCHAR(20) DEFAULT 'pending',
        FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
      )
    `);
    
    // 创建用户表
    await connection.query(`
      CREATE TABLE IF NOT EXISTS users (
        id INT AUTO_INCREMENT PRIMARY KEY,
        username VARCHAR(50) NOT NULL UNIQUE,
        password VARCHAR(100) NOT NULL,
        created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
      )
    `);
    
    // 初始化管理员账号
    await connection.query(`
      INSERT IGNORE INTO users (username, password)
      VALUES ('admin', '123456')
    `);
    
    console.log('数据库表结构初始化成功');
    connection.release();
  } catch (error) {
    console.error('数据库表结构初始化失败:', error.message);
  }
}

module.exports = {
  pool,
  testConnection,
  initDatabase
};